/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.sys.controller;

import io.renren.common.exception.JshException;
import io.renren.common.utils.R;
import io.renren.modules.sys.dao.TenantMapper;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.entity.Tenant;
import io.renren.modules.sys.form.SysLoginForm;
import io.renren.modules.sys.service.SysCaptchaService;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.service.SysUserTokenService;
import io.renren.modules.sys.service.TenantService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

/**
 * 登录相关
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
public class SysLoginController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserTokenService sysUserTokenService;
	@Autowired
	private SysCaptchaService sysCaptchaService;
	@Value("127.0.0.1")
	String domainName;
	/**
	 * 验证码
	 */
	@GetMapping("captcha.jpg")
	public void captcha(HttpServletResponse response, String uuid)throws IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//获取图片验证码
		BufferedImage image = sysCaptchaService.getCaptcha(uuid);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 登录
	 */
	@PostMapping("/sys/login")
	public Map<String, Object> login(@RequestBody SysLoginForm form, HttpServletRequest request)throws IOException {


		boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
		if(!captcha){
			return R.error("验证码不正确");
		}

		//用户信息
		SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
			System.out.println("密码1"+new Sha256Hash(form.getPassword(), user.getSalt()).toHex());
			System.out.println("密码2"+user.getPassword());
			return R.error("账号或密码不正确");
		}



		//账号锁定
		if(user.getStatus() == 0){
			return R.error("账号已被锁定,请联系管理员");
		}

		//生成token，并保存到数据库
		R r = sysUserTokenService.createToken(user.getUserId());
		return r;
	}


	/**
	 * 退出
	 */
	@PostMapping("/sys/logout")
	public R logout( HttpServletRequest request, HttpServletResponse response) {
		Cookie memNameStatusCookie = new Cookie("JSESSIONID",null);
//		memNameStatusCookie.setPath("/");
		memNameStatusCookie.setValue(null);
//		memNameStatusCookie.setDomain(domainName);
		response.addCookie(memNameStatusCookie);
		memNameStatusCookie.setMaxAge(0);
//		session.removeAttribute(AuthServerConstant.LOGIN_USER);
		sysUserTokenService.logout(getUserId());
		return R.ok();
	}



//	/**
//	 * 注册
//	 */
//	@PostMapping("/sys/registerUser")
//	public Map<String, Object> registerUser(@RequestBody SysLoginForm form, HttpServletRequest request)throws IOException {
//		boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
//		if(!captcha){
//			return R.error("验证码不正确");
//		}
//		//用户信息
//		SysUserEntity user = sysUserService.queryByUserName(form.getUsername());
//
//		//账号不存在、密码错误
////		if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
////			System.out.println("密码1"+new Sha256Hash(form.getPassword(), user.getSalt()).toHex());
////			System.out.println("密码2"+user.getPassword());
////			return R.error("账号或密码不正确");
////		}
//		if(user!=null){
//			return R.error("用户名已存在");
//		}
//       //将数据保存在用户表
////		sysUserService.insertUser();
//        //将数据保存在租户表
//		R r=R.ok().put("result","注册成功" );
//		try{
//			sysUserService.insertTenantAndUser(form.getUsername(),form.getPassword());
//			 r = R.ok().put("result","注册成功" );
//		}catch(Exception e){
//			JshException.readFail(logger, e);
//			r = R.error().put("result","注册失败" );
//		}
//		return r;
//	}
}









